<?php
/**
 * Regex.php
 *
 * @category    Madoqua
 * @package     Controller
 */

/** base class */
require_once 'Zend/Controller/Router/Route/Regex.php';

/**
 * Madoqua_Controller_Router_Route_Regex
 *
 * @category    Madoqua
 * @package     Controller
 */
class Madoqua_Controller_Router_Route_Regex extends Zend_Controller_Router_Route_Regex
{
    /**
     * Instantiates route based on passed Zend_Config structure
     *
     * @param Zend_Config $config Configuration object
     */
    public static function getInstance(Zend_Config $config)
    {
        $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
        $map = ($config->map instanceof Zend_Config) ? $config->map->toArray() : array();
        $map = array_flip($map);
        $reverse = (isset($config->reverse)) ? $config->reverse : null;
        return new self($config->route, $defs, $map, $reverse);
    }
    
    /**
     * Maps numerically indexed array values to it's associative mapped counterpart.
     * Or vice versa. Uses user provided map array which consists of index => name
     * parameter mapping. If map is not found, it returns original array.
     *
     * Method strips destination type of keys form source array. Ie. if source array is
     * indexed numerically then every associative key will be stripped. Vice versa if reversed
     * is set to true.
     *
     * @param array $values Indexed or associative array of values to map
     * @param boolean $reversed False means translation of index to association. True means reverse.
     * @param boolean $preserve Should wrong type of keys be preserved or stripped.
     * @return array An array of mapped values
     */
    protected function _getMappedValues($values, $reversed = false, $preserve = false)
    {
        if (count($this->_map) == 0) {
            return $values;
        }

        $return = array();

        foreach ($values as $key => $value) {
            if (is_int($key) && !$reversed) {
                if (array_key_exists($key, $this->_map)) {
                    $index = $this->_map[$key];
                } elseif (false === ($index = array_search($key, $this->_map))) {
                    $index = $key;
                }
                $return[$index] = $values[$key];
            } elseif ($reversed) {
                $index = (!is_int($key)) ? array_search($key, $this->_map, true) : $key;
                if (false !== $index) {
                    $return[$index] = $values[$key];
                } elseif (isset($this->_map[$key])) {
                    //non-numerical setup
                    $return[$key] = $this->_map[$key];
                }
            } elseif ($preserve) {
                $return[$key] = $value;
            }
        }

        return $return;
    }
}